package com.yinhai.redis.cluster;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.zookeeper.ZooKeeper;

import redis.clients.jedis.Jedis;

import com.yinhai.redis.cluster.event.ClusterEvent;
import com.yinhai.redis.cluster.event.EventBus;
import com.yinhai.redis.cluster.model.ShardHolder;

/**
 * 
 * @author dreamlee
 *
 */
public class HeartBeatThread extends Thread {
	
	private List<ShardHolder> holders=new ArrayList<ShardHolder>();
	
	private ZooKeeper zk;
	
	
	public ZooKeeper getZk() {
		return zk;
	}

	public void setZk(ZooKeeper zk) {
		this.zk = zk;
	}

	public List<ShardHolder> getHolders() {
		return holders;
	}

	public void setHolders(List<ShardHolder> holders) {
		this.holders = holders;
	}

	@Override
	public void run() {
		List<ShardHolder> tmps=new ArrayList<ShardHolder>();
		tmps.addAll(holders);
		while(true){
			try{
				for(Iterator<ShardHolder> iter=tmps.iterator();iter.hasNext();){
					ShardHolder holder=iter.next();
					Jedis jedis=holder.getPool().getResource();
					try{
						jedis.ping();
					}catch(Exception e){
						//服务器宕机
						ClusterEvent event=new ClusterEvent();
						event.setType(ClusterEvent.SHARD_REMOVED);
						event.setData(holder);
						event.setTarget(this);
						EventBus.getInstance().publishEvent(event);
						iter.remove();
					}finally{
						holder.getPool().returnResource(jedis);
					}
				}
			}catch(Exception e){
			}
			try {
				TimeUnit.SECONDS.sleep(5);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
